/*int main()
{
    pid_t child_pid;
    int status;

    //创建子进程
    child_pid = fork();
    if(child_pid<0)
    {
        perror("fork faile");
        exit(EXIT_FAILURE);
    }
    else if(child_pid == 0)
    {
        printf("i am child process\n");
        sleep(5);//等待五秒
        exit(42);
    }
    else
    {
        printf("Parent is waiting for child process %d to terminate...\n",child_pid);

        if(waitpid(child_pid,&status,0)!=child_pid)
        {
            perror("waitpid failed");
            exit(EXIT_FAILURE);
        }

        if(WIFEXITED(status))
        {
             printf("Child process exited with status %d\n", WEXITSTATUS(status));
        }
        else if(WIFSIGNALED(status))
        {
            int signum = WTERMSIG(status);
            printf("Child process terminated by signal %d\n", signum);
        }
        #ifdef WCOREDUMP
        if (WCOREDUMP(status))
        {
            printf("Core dump was produced\n");
        }
        else
        {
            printf("No core dump was produced\n");
        }
         #else
            printf("Core dump information not available\n");
            #endif
        } else {
            printf("Child process did not exit normally\n");
    }
}
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

int main()
{
    pid_t child_pid;
    int status;

    // 创建子进程
    child_pid = fork();
    if (child_pid < 0)
    {
        perror("fork failed");
        exit(EXIT_FAILURE);
    }
    else if (child_pid == 0)
    {
        // 子进程代码
        printf("i am child process\n");
        sleep(5); // 等待5秒
        exit(42); // 以退出码42结束子进程
    }
    else
    {
        // 父进程代码
        printf("Parent is waiting for child process %d to terminate...\n", child_pid);

        // 使用waitpid等待子进程结束
        if (waitpid(child_pid, &status, 0) != child_pid)
        {
            perror("waitpid failed");
            exit(EXIT_FAILURE);
        }

        // 分析子进程的退出状态
        if (WIFEXITED(status))
        {
            printf("Child process exited with status %d\n", WEXITSTATUS(status));
        }
        else if (WIFSIGNALED(status))
        {
            int signum = WTERMSIG(status);
            printf("Child process terminated by signal %d\n", signum);
#ifdef WCOREDUMP
            if (WCOREDUMP(status))
            {
                printf("Core dump was produced\n");
            }
            else
            {
                printf("No core dump was produced\n");
            }
#else
            printf("Core dump information not available\n");
#endif
        }
        else
        {
            printf("Child process did not exit normally\n");
        }
    }

    return 0;
}
